% Penalized2
% Penalized2 has a global optimal at 0 in range [-50,50]
function result = Penalized2(x)
total_a = 0;
len = length(x);
for i = 1:len - 1
    temp = (x(i) - 1)^2 * (1 + sin(3*pi*x(i+1))^2) + ...
                    (x(len) - 1)^2 * (1 + sin(2*pi*x(i+1))^2);
    total_a = total_a + temp;            
end
total_b = 0;
for i = 1:len
    total_b = total_b + u(x(i), 5, 100, 4);
end
result = (1/10) * (sin(pi*x(1))^2 + total_a) + total_b;
end

function result = u(x_ith, a, k ,m)
if x_ith > a
    u = k * (x_ith - a)^m;
elseif x_ith >= -a
    u = 0;
else
    u = k * (-x_ith - a)^m;
end
result = u;
end